package com.elcl.widget.view;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.elcl.adapter.ViewPageAdapter;
import com.elcl.andbaselibrary.R;
import com.elcl.util.viewutils.ImageViewUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author LCL 导航页性质的ViewPager，同时可设置自动滑动的效果
 *         注意:在调用的时候，最后要showView()方法
 */
public class ABViewPager extends LinearLayout {
    private Context ctx;
    private View view;
    private LinearLayout linearLayout;

    private List<View> list_views;//添加的自定义的视图

    private int curPage = 0;
    private int[] array_mainPicLocal;// 主视图的图片（添加的本地）
    private List<String> list_mainPicNet;// 主视图的图片（网上）
    private int[] pointPic;
    private int pointGravity = 0;// 点的位置
    private int pointMarginDimen = 0;// 点点之间的距离
    private int pointMarginBottomDimen = 0;// 点距底部的距离
    private boolean isAutoScroll = false;

    private int len = 0;// 添加的View的长度
    private boolean isMainPicNet = false;// 是否为网络图片(传入的类型为字符类型的网络图片地址)
    private boolean isAddView = false;// 是否为自定义的View
    private boolean isPointVisible = true;// 下面的显示页数的小圆点是否为可见的

    public ABViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        ctx = context;
    }

    public ABViewPager(Context context) {
        super(context);
        ctx = context;
    }

    public void show() {
        view = LayoutInflater.from(ctx).inflate(R.layout.main_view_pager, null);
        linearLayout = (LinearLayout) view.findViewById(R.id.linearlayout);
        initView();
        initPagerAdapter();
        addView(view, new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
    }

    private void initView() {
        if (isPointVisible) {//如果圆点是可见的话，添加小圆点
            addPointView(0);
        }
        if (!isAddView) {// 如果不是添加的View类型的，则添加imagView类型的view
            addMainPic();
        }
        if (isAutoScroll) {//添加自动轮播的线程
            addViewPagerTimer();
        }
    }

    private ScheduledExecutorService executorService;

    private void addViewPagerTimer() {
        executorService = Executors
                .newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(runnable, 2, 2, TimeUnit.SECONDS);
    }

    /**
     * 添加主视图的图片
     */
    private void addMainPic() {
        list_views = new ArrayList<View>();
        if (isMainPicNet) {
            for (int i = 0; i < len; i++) {
                RelativeLayout relativeLayout = new RelativeLayout(ctx);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

                ImageView img = new ImageView(ctx);
                if (errorDrawable == 0)//如果有错误图片的话，加载错误图片，否则的话，不加载
                    Glide.with(ctx).load(list_mainPicNet.get(i)).into(img);
                else
                    Glide.with(ctx).load(list_mainPicNet.get(i)).error(errorDrawable).into(img);

                img.setScaleType(ScaleType.FIT_XY);
                img.setOnClickListener(listener);
                relativeLayout.addView(img, layoutParams);

                list_views.add(relativeLayout);
            }
        } else {
            for (int i = 0; i < len; i++) {
                ImageView imageView = new ImageView(ctx);
                Glide.with(ctx).load(array_mainPicLocal[i]).into(imageView);
//                imageView.setImageBitmap(ImageViewUtils.readBitMap(ctx, array_mainPicLocal[i]));
                imageView.setScaleType(ScaleType.FIT_XY);
                imageView.setOnClickListener(listener);
                list_views.add(imageView);
            }
        }
    }

    /**
     * 添加小圆点
     */
    private void addPointView(int position) {
        LayoutParams layoutParams = new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        // 设置小圆点的间距
        if (pointMarginDimen == 0) {
            layoutParams.leftMargin = 10;
            layoutParams.rightMargin = 10;
        } else {
            layoutParams.leftMargin = pointMarginDimen;
            layoutParams.rightMargin = pointMarginDimen;
        }

        // 设置小圆点的位置
        if (pointGravity != 0 || pointMarginBottomDimen != 0) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linearLayout
                    .getLayoutParams();
            if (pointGravity != 0) {
                params.addRule(pointGravity);
            }
            if (pointMarginBottomDimen != 0) {
                params.bottomMargin = pointMarginBottomDimen;
            }
            linearLayout.setLayoutParams(params);
        }

        if (linearLayout.getChildCount() > 0) {
            linearLayout.removeAllViews();
        }
        for (int i = 0; i < len; i++) {
            ImageView img = new ImageView(ctx);
            img.setLayoutParams(layoutParams);
            if (position == i) {
                img.setBackgroundDrawable(getResources().getDrawable(
                        pointPic == null ? R.drawable.pic_1 : pointPic[0]));
            } else {
                img.setBackgroundDrawable(getResources().getDrawable(
                        pointPic == null ? R.drawable.pic_2 : pointPic[1]));
            }
            linearLayout.addView(img);
        }
    }

    ViewPager viewPager = null;
    private ViewPageAdapter pageAdapter;

    private void initPagerAdapter() {
        if (null == viewPager){
            viewPager = (ViewPager) view.findViewById(R.id.view_pager);
            pageAdapter = new ViewPageAdapter(list_views);
            viewPager.setAdapter(pageAdapter);
            viewPager.setOnPageChangeListener(new MyPagerListener());
        }else{
            pageAdapter.notifyDataSetChanged();
        }
    }

    public class MyPagerListener implements OnPageChangeListener {// 位置是从0开始的

        @Override
        public void onPageScrollStateChanged(int arg0) {// arg0
            // ==1的时辰默示正在滑动，arg0==2的时辰默示滑动完毕了，arg0==0的时辰默示什么都没做。

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {// arg0
            // :当前页面，及你点击滑动的页面,arg1:当前页面偏移的百分比,arg2:当前页面偏移的像素位置
        }

        @Override
        public void onPageSelected(int arg0) {// 此方法是页面跳转完后得到调用，arg0是你当前选中的页面的Position
            if (isPointVisible) {
                addPointView(arg0);
            }
            curPage = arg0;
            if (null != viewpagerSelected) {
                viewpagerSelected.pageSelected(arg0);
            }
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            curPage = (curPage + 1) % len;// 实现最后一页跳到最后一页的循环
            handler.sendEmptyMessage(0);
        }
    };

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                viewPager.setCurrentItem(curPage, true);
            }
        }

    };

    /**
     * 开始滑动
     */
    public void setAutoScroll() {
        isAutoScroll = true;
    }

    /**
     * 设置主视图的图片(int类型的本地图片)
     */
    public void addMainPic(int[] drawables) {
        len = drawables.length;
        this.array_mainPicLocal = drawables;
    }

    /**
     * 设置主视图的图片(字符串类型的网络地址)
     */
    public void addMainPic(List<String> drawables) {
        len = drawables.size();
        isMainPicNet = true;
        this.list_mainPicNet = drawables;
    }

    /**
     * 设置主视图的view
     */
    public void addView(List<View> list_views) {
        len = list_views.size();
        isAddView = true;
        this.list_views = list_views;
    }

    /**
     * 设置显示的点的图片,int[0]是选中页的图片
     */
    public void addPointPic(int[] pointPic) {
        this.pointPic = pointPic;
    }

    /**
     * 设置小圆点的图片为不可见
     */
    public void setPointInvisible() {
        isPointVisible = false;
    }

    /**
     * 设置点与点之间的距离
     */
    public void setPointMarginDimen(int pointMarginDimen) {
        this.pointMarginDimen = pointMarginDimen;
    }

    /**
     * 设置点的位置(左下，或者右下)eg:RelativeLayout.ALIGN_PARENT_RIGHT
     */
    public void setPointGravity(int pointGravity) {
        this.pointGravity = pointGravity;
    }

    /**
     * 设置点距离底部的位置
     */
    public void setPointMaginBottomDimen(int pointMarginBottomDimen) {
        this.pointMarginBottomDimen = pointMarginBottomDimen;
    }

    private OnClickListener listener;

    public void setOnViewPagerClickListener(OnClickListener listener) {
        this.listener = listener;
    }

    //获取viewpager
    public ViewPager getViewPager() {
        return viewPager;
    }

    public interface ViewpagerSelected {
        void pageSelected(int curPage);
    }

    private ViewpagerSelected viewpagerSelected;

    public void setOnViewPagerSelectedListener(ViewpagerSelected viewpagerSelected) {
        this.viewpagerSelected = viewpagerSelected;
    }

    /**
     * 获取当前的页数
     */
    public int getCurPage() {
        return curPage;
    }

    private int errorDrawable = 0;

    //图片加载错误的
    public void setLoadErrorPic(int errorDrawable) {
        this.errorDrawable = errorDrawable;
    }

}
